package com.kotlin.library.data.net

import com.kotlin.library.common.BaseConstant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *
 * USER: zjw
 * DATA: 2018/11/27 0027
 * TIME: 下午 6:22
 * retrofit的工厂类,单利 私有构造方法 ,伴随对像
 *  伴生对像,可以直接类名.调用,
 *  by lazy{}委托 懒加载,只能用于val类型,因为没有setVaule()方法,只有别用到的时候才初始化,本身就是线程安全的
 */
class RetrofitFactory private constructor() {
    companion object {
        val instace: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private var retrofit: Retrofit
    private var interceptor: Interceptor

    init {

        interceptor = Interceptor { chain ->
            var request = chain.request().newBuilder()
                .addHeader("Content_Type", "application/json")
                .addHeader("charset", "UTF-8")
                .build()
            chain.proceed(request)
        }

        retrofit = Retrofit.Builder()
            .baseUrl(BaseConstant.SERVICE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(getOkhttpClient())
            .build()
    }

    private fun getOkhttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .addInterceptor(getLogInterceptor())
            .build()
    }

    private fun getLogInterceptor(): Interceptor {
        var logInterceptor = HttpLoggingInterceptor()
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return logInterceptor
    }

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }
}